<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校" prop="schoolName">
        <el-input
          v-model="queryParams.schoolName"
          placeholder="请输入学校"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择发布状态" clearable size="small" >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

        <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['forum:dynamic:add']"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['forum:dynamic:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['forum:dynamic:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleRelease"
          v-hasPermi="['forum:dynamic:release']"
        >发布</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="error"
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleOffShelf"
          v-hasPermi="['forum:dynamic:offShelf']"
        >下架</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dynamicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="视频图片" align="center" prop="logo" >
        <template slot-scope="scope">
          <el-image :src="base_url+scope.row.logo" fit="contain" style="width: 50px;height: 50px;" :preview-src-list="[base_url+scope.row.logo]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="name" >
        <template slot-scope="scope">
          <span style="cursor: pointer;color:blue" @click="checkMedia(scope.row)">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="schoolName" />
      <el-table-column label="时长/s" align="center" prop="description" />
      <el-table-column label="点赞数量" align="center" prop="zanNum" />
      <el-table-column label="收藏数量" align="center" prop="collectNum" />
      <el-table-column label="观看人数" align="center" prop="personNum" />
      <el-table-column label="观看次数" align="center" prop="viewNum" />
      <el-table-column label="发布时间" align="center" prop="releaseTime" :show-overflow-tooltip="true"/>
      <el-table-column label="发布状态" align="center" prop="status" :formatter="statusFormat" >
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark"  :content="scope.row.status == 2 ? scope.row.reason:''" placement="top" v-if="scope.row.status == 2">
            <span>{{ statusFormat(scope.row) }}</span>
          </el-tooltip>
          <span v-else>{{ statusFormat(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
      <template slot-scope="scope">
        <el-input-number
          v-model="scope.row.sort"
          placeholder="请输入排序"
          clearable
          size="small"
          style="width: 100px"
         @change="change(scope.row)"
        />
      </template>

      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommend">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isRecommend"
              :active-value="1"
              :inactive-value="0"
              @change="recommendHandle(scope.row)"
            ></el-switch>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改论坛-动态对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="close('previewVideo')">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="name">
          <el-input v-model="form.name" placeholder="请输入标题" maxlength="20" :disabled="form.status == 1"/>
        </el-form-item>
        <el-form-item label="视频内容" prop="content">
          <el-input v-model="form.content" placeholder="请输入内容" maxlength="50" :disabled="form.status == 1"/>
        </el-form-item>
        <el-form-item label="封面图" prop="logo">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :limit="1"
              :file-list="fileList"
              :headers="headers"
              :disabled="form.status == 1"
              :before-upload="checkUpload">
              <img v-if="files" :src="base_url+files" class="avatar" width="100px" height="100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
<!--        <el-form-item label="描述" prop="description">-->
<!--          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
        <el-form-item label="视频" prop="mediaFile">
          <el-upload
            ref="media"
            :action="url+ '/media'"
            :headers="headers"
            :on-success="handleSuccess"
            :before-upload="handleCheck"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="1"
            accept=".mp4,.3gp,.m3u8"
            :disabled="form.status == 1"
            :file-list="mediaFileList">
            <video id="previewVideo" v-if="mediaFiles" autoplay controls loop class="video-box"
                   :src="base_url+mediaFiles">
              您的浏览器不支持视频播放</video>
              <el-button v-else size="small" type="primary">点击上传</el-button>
              <span v-if="!mediaFiles" style="color: red"> 文件大小只允许上传{{big}}M 时长在{{short}}~{{long}}s</span>

          </el-upload>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="reason" v-if=" form.status == 2 && form.reason">
          <span >{{ form.reason }}</span>
        </el-form-item>
        <el-form-item label="封面图" prop="pics" v-show="false">
          <el-input v-model="form.pics" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog  title="视频详情" :visible.sync="play" width="350px" append-to-body @close="close('videoPreview')">
      <video id="videoPreview" autoplay controls loop class="video-box" :src="base_url+mediaFile">您的浏览器不支持视频播放</video>
    </el-dialog>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import {viewConfig} from "@/api/wx/config";
  import { listGxDynamic, getGxDynamic,releaseGx,offShelfGx, delDynamic, addGxDynamic, updateDynamic, exportDynamic,recommend } from "@/api/forum/dynamic";

export default {
  name: "Dynamic",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 论坛-动态表格数据
      dynamicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      play:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        content: undefined,
        circleId: undefined,
        logo: undefined,
        status: undefined,
        wxUserId: undefined,
        wxClientId: undefined,
        sort: undefined,
        contentType: undefined,
        pics: undefined,
        description: undefined,
        mediaFile: undefined,
        pageView: undefined,
        skipUrl: undefined,
        dataType: undefined,
        releaseTime: undefined,
        commentNum: undefined,
        collectNum: undefined,
        zanNum: undefined,
        reason: undefined,
        deptId: undefined,
        schoolName:undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name:[
          {required: true, message: "请输入视频标题", trigger: "blur"}
        ],
        content: [
          {required: true, message: "请输入视频内容", trigger: "blur"}
        ],
        logo:[
          {required :true,message:"请上传封面图",trigger:'blur'}
        ],
        mediaFile:[
          {required :true,message:"请上传视频",trigger:'blur'}
        ]
      },
      statusOptions:[],
      mediaFile:undefined,
      base_url:process.env.VUE_APP_BASE_API,
      url:process.env.VUE_APP_BASE_API + "/common/upload",
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      fileList:[],
      mediaFileList:[],
      files:undefined,
      mediaFiles:undefined,
      configList:[],
      short:1,
      long:2,
      big:1
    };
  },
  created() {
    // 用户状态字典翻译
    this.getDicts("forum_dynamic_status").then(response => {
      this.statusOptions = response.data;
    });
    viewConfig({
      wxClientId: this.$route.query.id
    }).then(response => {
      this.configList = response.data;
      this.configList.map(item=>{
        if(item.code === "c"){
          this.short = item.value
        }else if(item.code === "d"){
          this.long = item.value
        }else if(item.code === "e"){
          this.big = item.value
        }
      })
    });
    this.getList();
  },
  methods: {
    change(item){
      updateDynamic(item).then(res=>{
        if(res.code === 200){
          this.$message.success("修改成功")
        }
      })
    },
    checkMedia(row){
      this.mediaFile = undefined;
      if(row.mediaFile){
        this.mediaFile = row.mediaFile;
        this.play = true;
      }else{
        this.msgError("视频播放失败")
      }
    },
    close(id){
      var videoElement = document.getElementById(id);
      if(videoElement){
        videoElement.pause();
        videoElement.removeAttribute('src'); // empty source
        videoElement.load();
      }
    },
    // 状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    recommendHandle(row) {
      let text = row.isRecommend === 0 ? "取消推荐" : "推荐";
      this.$confirm('确认要' + text + '吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return recommend(row.id, row.isRecommend);
      }).then(() => {
        this.getList();
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.isRecommend = row.isRecommend === 0 ? 1 : 0;
      });
    },
    /** 查询论坛-动态列表 */
    getList() {
      this.loading = true;
      listGxDynamic(this.queryParams).then(response => {
        this.dynamicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        content: undefined,
        circleId: undefined,
        logo: undefined,
        status: "0",
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        wxUserId: undefined,
        wxClientId: undefined,
        sort: undefined,
        contentType: undefined,
        pics: undefined,
        description: undefined,
        mediaFile: undefined,
        pageView: undefined,
        skipUrl: undefined,
        dataType: undefined,
        releaseTime: undefined,
        commentNum: undefined,
        collectNum: undefined,
        zanNum: undefined,
        reason: undefined,
        deptId: undefined,
      };
      this.resetForm("form");
      this.mediaFiles = undefined;
      this.files = undefined;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;

      this.title = "添加视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let that = this;
      this.reset();
      const id = row.id || this.ids;
      getGxDynamic(id).then(response => {
        this.form = response.data;
        this.files = response.data.logo;
        this.mediaFiles = response.data.mediaFile;
        this.mediaFileList =[{path:that.base_url + response.data.mediaFile,name:response.data.name}];
        this.open = true;
        this.title = "修改视频";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            this.form.status = '0';
            updateDynamic(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.$refs.media.clearFiles();
                this.$refs.upload.clearFiles();
                this.close();
              }
            });
          } else {
            addGxDynamic(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.$refs.media.clearFiles();
                this.$refs.upload.clearFiles();
                this.close();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除视频编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDynamic(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 发布按钮操作 */
    handleRelease(row) {
      const ids = row.id || this.ids;
      this.$prompt('请输入发布原因', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        return releaseGx(ids,value);
      }).then(() => {
        this.getList();
        this.msgSuccess("发布成功");
      }).catch(function() {});
    },
    /** 下架按钮操作 */
    handleOffShelf(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认下架视频编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return offShelfGx(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("下架成功");
      }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有视频数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportDynamic(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    //视频移除
    handleRemove(file, fileList) {
      this.mediaFileList = [];
      this.mediaFiles = '';
      this.form.mediaFile = undefined;
      this.$refs.media.clearFiles();
    },
    // //视频移除询问
    // beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除 ${ file.name }？`);
    // },

    /**获取 视频对象**
      let fileVIdeo =  document.getElementById("upload").files[0]

    **获取时长 是异步的，可将其封装为priomise**/
  //这里的需求是 时长 10-60秒  大小 30M
  // 判断时长
  getVideoTime(file) {
    return new Promise((resolve,reject)=>{
      let url = URL.createObjectURL(file);
      let audioElement = new Audio(url);
      audioElement.addEventListener("loadedmetadata", (event)=> {
        let duration = parseInt(audioElement.duration);
        // 大小 时长
        if (duration > this.long || duration < this.short ) {
          //超过需求限制
          this.$message.error(`上传视频时长必须在`+this.short+`-`+this.long+`s之间!`);
          this.mediaFileList.pop();
          resolve(false)
        } else {
          this.form.description = duration;
          resolve(true)
        }
      });
    })
  },

  //视频上传前确认
    handleCheck(file){
      console.log("文件类型", file);
      const imgType = file.type;
      //图片不大于2M
      const isLtSize = file.size / 1024 / 1024 < this.big;
      if (['video/mp4','video/3gp','video/m3u8'].indexOf(imgType) === -1) {
        this.$message.error('上传视频只能是 MP4、3GP、M3U8 格式!');
        return false;
      }
      if(!isLtSize){
        this.$message.error(`上传视频大小不能超过`+this.big+`MB!`);
        return false;
      }
      this.getVideoTime(file).then(res=>{
        return res;
      })
    },
    //视频上传成功
    handleSuccess(response, file, fileList){
    this.$nextTick(function () {
      if(this.form.description){
        this.form.mediaFile = response.fileName;
        this.mediaFiles = response.fileName;
        this.chooseVideo();
      }
    });
    },
    chooseVideo() {
    var that = this;
    //获取video标签
      this.$nextTick(function(){
        var videoElement = document.getElementById("previewVideo");
        videoElement.src =this.base_url+ this.form.mediaFile;
        videoElement.addEventListener("play", function() {
          var canvas = document.createElement("canvas");
          canvas.width = videoElement.videoWidth;
          canvas.height = videoElement.videoHeight;
          canvas.getContext("2d").drawImage(videoElement, 0, 0, canvas.width, canvas.height);
          var firstFrame = canvas.toDataURL("image/png"); //第一帧图片url
          //base64转成blob
          var blob = that.dataURLtoFile(firstFrame,"image/png");
          that.uploadImg(blob);
        })
      })

  },
    //base64 to blob
    dataURLtoFile(dataURI, type) {
      let binary = atob(dataURI.split(",")[1]);
      let array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
    // 图片上传
    uploadImg(fileData) {
      var that = this;
      let formData = new FormData();
      formData.append("file",fileData, new Date() + ".png");
      this.$axios.post(
          this.url,
          formData,
          {
            headers: that.headers,
          }
        )
        .then((res) => {
          console.log(res.data.fileName)
          that.form.pics = res.data.fileName
        });
    },
    //图片上传成功
    /** 上传成功后的回调 */
    uploadSuccess(response, file, fileList) {
      this.form.logo = response.fileName;
      this.files = response.fileName;
      this.msgSuccess("上传成功")
    },
    /** 上传之前的校验 */
    checkUpload(file) {
      console.log("文件类型", file);
      const imgType = file.type;
      //图片不大于2M
      const isLtSize = file.size / 1024 / 1024 < 2;
      if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
        this.$message.error('上传图片只能是 JPG、PNG、GIF格式!');
        return false;
      }
      if (!isLtSize) {
        this.$message.error(`上传图片大小不能超过2MB!`);
        return false;
      }
    },
    handleExceed(){
      this.msgError("请先移除已有视频后上传");
      return;
    }

  }
};
</script>
<style>
  .video-box{
    width: 300px;
    height: 400px;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px #cccccc dashed;
    border-radius: 5px;
  }
  .el-upload__tip {
    line-height: 1.2;
  }
  .uploadBtn{
    height: 40px;
  }
</style>
